var express = require('express');
var router = express.Router();
let db = require('../db/index')

/* GET home page. */
router.get('/', async function (req, res, next) {
  let {society_id} = req.query;
  let memberCount = await new Promise(resolve => {
    if(society_id === '0'){
      db.query(`SELECT count(id) as total FROM account`, function (err, [{total}]) {
        resolve(total)
      })
    }else{
      db.query(`SELECT count(id) as total FROM account WHERE society_id = ${society_id}`, function (err, [{total}]) {
        resolve(total)
      })
    }
  })
  let activityCount = await new Promise(resolve => {
    if(society_id === '0'){
      db.query(`SELECT count(id) as total FROM activity`, function (err, [{total}]) {
        resolve(total)
      })
    }else{
      db.query(`SELECT count(id) as total FROM activity WHERE society_id = ${society_id}`, function (err, [{total}]) {
        resolve(total)
      })
    }
  })
  let talkCount = await new Promise(resolve => {
    if(society_id === '0'){
      db.query(`SELECT count(id) as total FROM talk`, function (err, [{total}]) {
        resolve(total)
      })
    }else{
      db.query(`SELECT count(id) as total FROM talk WHERE society_id = ${society_id}`, function (err, [{total}]) {
        resolve(total)
      })
    }
  })
  let articleCount = await new Promise(resolve => {
    if(society_id === '0'){
      db.query(`SELECT count(id) as total FROM article`, function (err, [{total}]) {
        resolve(total)
      })
    }else{
      db.query(`SELECT count(id) as total FROM article WHERE society_id = ${society_id}`, function (err, [{total}]) {
        resolve(total)
      })
    }
  })
  let gradeList = await new Promise(resolve => {
    if(society_id === '0'){
      var sql = `SELECT stu_code FROM account`
    }else{
      var sql = `SELECT stu_code FROM account WHERE society_id = ${society_id}`
    }
    db.query(sql, function (err, rows) {
      let res = [[], []];
      rows.map(item => {
        let num = item.stu_code.slice(0, 4)
        let index = res[0].findIndex(item=>item === num)
        if (index === -1) {
          res[0].push(num);
          res[1].push(1);
        }else{
          res[1][index] += 1;
        }
      })
      resolve(res);
    })
  })

  res.send({
    code: 200,
    data: {
      memberCount, activityCount, talkCount, articleCount,gradeList
    }
  })
});

module.exports = router;
